package org.apache.commons.httpclient.contrib.ssl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocketFactory;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.net.ssl.SSLContext;
import com.sun.net.ssl.TrustManager;

public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory {

    private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class);

    private static SSLSocketFactory getEasySSLSocketFactory() {
        SSLContext context = null;
        try {
            context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.toString());
        }
        return context.getSocketFactory();
    }

    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException,
                                                                                              UnknownHostException {
        Socket socket = getEasySSLSocketFactory().createSocket(host, port, clientHost, clientPort);

        return socket;
    }

    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return getEasySSLSocketFactory().createSocket(host, port);
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,
                                                                                        UnknownHostException {
        return getEasySSLSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort,
                               HttpConnectionParams params) throws IOException, UnknownHostException,
                                                            ConnectTimeoutException {
        return createSocket(host, port, clientHost, clientPort);
    }
}
